package net.xdclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeType;
import net.xdclass.feign.CouponFeignService;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.mapper.UserMapper;
import net.xdclass.model.LoginUser;
import net.xdclass.model.UserDO;
import net.xdclass.request.LoginRequest;
import net.xdclass.request.NewUserCouponRequest;
import net.xdclass.request.UserRegisterRequest;
import net.xdclass.service.NotifyService;
import net.xdclass.service.UserService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.util.JwtUnit;
import net.xdclass.vo.UserVo;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CouponFeignService couponFeignService;
    @Override
    @Transactional
    public JsonData registerUser(UserRegisterRequest userRegisterRequest) {
        boolean flag = false;
        flag = notifyService.checkCode(userRegisterRequest.getCode(), SendCodeType.USER_REGISTER_MAIL, userRegisterRequest.getMail());
        if (!flag){
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }else{
            UserDO userDO = new UserDO();
            BeanUtils.copyProperties(userRegisterRequest,userDO);
            userDO.setCreateTime(new Date());
            userDO.setSecret("$1$"+CommonUtil.getStringNumRandom(8));
            String md5Crypt = Md5Crypt.md5Crypt(userDO.getPwd().getBytes(), userDO.getSecret());
            userDO.setPwd(md5Crypt);
            if(!mailUnique(userDO.getMail())) {
                userMapper.insert(userDO);
                userRegisterInitTask(userDO);
                //int i = 1/0;
                return JsonData.buildSuccess("用户注册成功");
            }else{
                return JsonData.buildResult(BizCodeEnum.MAIL_UNIQUE);
            }
        }
    }

    private boolean mailUnique(String mail){
        List<UserDO> UserDOMail = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", mail));
        return UserDOMail.size()>0?true:false;
    }

    @Override
    public JsonData login(LoginRequest loginRequest) {
        List<UserDO> userDOList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", loginRequest.getMail()));
        if (!CollectionUtils.isEmpty(userDOList)){
            UserDO userDO = userDOList.get(0);
            String md5Crypt = Md5Crypt.md5Crypt(loginRequest.getPwd().getBytes(), userDO.getSecret());
            if (md5Crypt.equals(userDO.getPwd())){
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(userDO,loginUser);
                String jwt = JwtUnit.getJwt(loginUser);
                return JsonData.buildSuccess(jwt);
            }else{
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        }else{
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    @Override
    public UserVo findUserDetail() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id", loginUser.getId()));
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userDO,userVo);
        return userVo;
    }

    /**
     * 用户注册，初始化福利信息
     */
    private void userRegisterInitTask(UserDO userDO) {
        NewUserCouponRequest newUserCouponRequest = new NewUserCouponRequest();
        newUserCouponRequest.setUserId(userDO.getId());
        newUserCouponRequest.setName(userDO.getName());
        JsonData jsonData = couponFeignService.addNewUserCoupon(newUserCouponRequest);
        if (jsonData.getCode() != 0) {
            throw new RuntimeException("发放新人优惠券失败");
        }
        log.info("发放新用户注册优惠券：{},结果{}",newUserCouponRequest.toString(),jsonData.toString());
    }
}
